package com.kele.dynamic;

import com.kele.ddl.CreateTable;

import java.sql.*;

/**
 * 根据mysql数据库字段动态创建实体类
 */
public class GenEntityMySQL {

    private String packageOutPath = "com.kele.entity";//指定实体生成所在包的路径
    private String javaName = "Student"; //.java文件名
    private String authorName = "kele";//作者名字
    private String tablename = "student";//表名
    private String[] colnames; // 列名数组
    private String[] colTypes; //列名类型数组
    private int[] colSizes; //列名大小数组
    private boolean f_util = false; // 是否需要导入包java.util.*
    private boolean f_sql = false; // 是否需要导入包java.sql.*

    //获得数据库连接
    static Connection conn;

    public static void main(String[] args) {

    }

    public GenEntityMySQL() throws SQLException {
        //获得数据库连接
        conn = CreateTable.getConnection();

        //获得要查询的表名
        String tableName = CreateTable.test();

        //sql语句
        String sql = "select * from" + tableName;

        Statement statement = conn.createStatement();

        ResultSet result = statement.executeQuery(sql);
        ResultSetMetaData metaData = result.getMetaData();
        //统计列
        int size = metaData.getColumnCount();
        //获得字段名数组
        colnames = new String[size];
        //获得字段类型数组
        colTypes = new String[size];

        //类型转换
        for (int i = 0; i < size; i++) {
            colnames[i] = metaData.getColumnName(i + 1);
            colTypes[i] = metaData.getColumnTypeName(i + 1);

            if (colTypes[i].equalsIgnoreCase("date") || colTypes[i].equalsIgnoreCase("timestamp")) {
                f_util = true;
            }
            if (colTypes[i].equalsIgnoreCase("blob") || colTypes[i].equalsIgnoreCase("char")) {
                f_sql = true;
            }
            colSizes[i] = metaData.getColumnDisplaySize(i + 1);
        }

        //类型转换
    }

    /**
     * 功能：生成实体类主体代码
     *
     * @param colnames
     * @param colTypes
     * @param colSizes
     * @return
     */
    private String parse(String[] colnames, String[] colTypes, int[] colSizes) {

        StringBuffer sb = new StringBuffer();

        //导入包名
        sb.append("package " + this.packageOutPath + ";\r\n");

        //判断是否导入工具包
        if (f_util) {
            sb.append("import java.util.Date;\r\n");
        }
        if (f_sql) {
            sb.append("import java.sql.*;\r\n");
        }

        return "null";


    }


}

